package org.example.socket网络编程.练习_拷贝文件夹;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

public class ByteBufferReader {
    private InputStream inputStream;
    private byte[] buffer = new byte[8192];
    private int bufferPos = 0;
    private int bufferSize = 0;

    public static void main(String[] args) throws IOException {
        try (FileInputStream fis = new FileInputStream("file.txt")) {
            ByteBufferReader reader = new ByteBufferReader(fis);
            String text;
            while ((text = reader.read()) != null) {
                System.out.print(text);
            }
        }
    }

    public ByteBufferReader(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String read() throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        while (true) {
            if (bufferPos >= bufferSize) {
                bufferSize = inputStream.read(buffer);
                bufferPos = 0;
                if (bufferSize == -1) break;
            }

            output.write(buffer[bufferPos]);
            bufferPos++;

            // 尝试解码已读取的字节
            byte[] bytes = output.toByteArray();
            String text = new String(bytes, StandardCharsets.UTF_8);
            // 检查是否有无效字符（如被截断的字节）
            if (isValidUTF8(bytes)) {
                output.reset();
                return text;
            }
        }
        return new String(output.toByteArray(), StandardCharsets.UTF_8);
    }

    private boolean isValidUTF8(byte[] bytes) {
        try {
            CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
            decoder.decode(ByteBuffer.wrap(bytes));
            return true;
        } catch (CharacterCodingException e) {
            return false;
        }
    }
}